package meadproperty.popup.actions;

import java.io.File;

import meadproperty.service.Constant;
import meadproperty.service.NewFileService;
import meadproperty.util.FileUtil;
import meadproperty.util.RunTimeUtil;
import meadproperty.views.PropertyViewer;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

public class NewAction implements IObjectActionDelegate {
	private IStructuredSelection select;
	private Shell shell;

	/**
	 * Constructor for Action1.
	 */
	public NewAction() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		IFile file = (IFile) select.getFirstElement();
		String path = file.getFullPath().toOSString();
		int index = path.lastIndexOf('\\');
		path = path.substring(0, index);
		NewFileService bs = new NewFileService();

		try {
			path = Constant.WORK_SPACE_PATH + path;
			Constant.ACTIVE_FILE_PATH = FileUtil.getOSFilePath(path + "/mead/")
					+ File.separatorChar;
			MessageDialog.openInformation(shell, "Constant.ACTIVE_FILE_PATH",
					Constant.ACTIVE_FILE_PATH);
			bs.createNew(Constant.ACTIVE_FILE_PATH);
		} catch (Exception e1) {
		}
		// Refresh the project here...
		RunTimeUtil.refreshProjects();
		Constant.ACTIVED_MARK = true;
		try {
			PlatformUI.getWorkbench().getActiveWorkbenchWindow()
					.getActivePage().showView(PropertyViewer.ID);
			Constant.PLUG_IN_VIEW_STATE = Constant.PLUG_IN_VIEW_STATE_OPEN;
		} catch (PartInitException e) {
			MessageDialog.openInformation(shell, "EXCEPTION",
					Constant.ACTIVE_FILE_PATH);
		}

	}

	public void selectionChanged(IAction action, ISelection selection) {
		select = (IStructuredSelection) selection;
	}

}
